package com.qc.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qc.common.SMSClient;
import com.qc.common.StringUtil;
import com.qc.common.Util;
import com.qc.entity.BusinessCategoryEntity;
import com.qc.entity.MerchantEntity;
import com.qc.service.BusinessCategoryService;
import com.qc.service.MerchantService;
import com.qc.service.UserService;

@Controller
public class MerchantLoginController {
    
    @Resource
    private UserService userService;
    
    @Resource
    private MerchantService merchantService;
    
    @Resource(name="businessCategoryService")
    private BusinessCategoryService businessCategoryService;

    /**
     * 商家登录首页
     * @return
     */
    @RequestMapping(value = "/toMerchantLogin", produces = "text/html;charset=UTF-8")
    public ModelAndView toMerchantLogin() {
        ModelAndView mav = new ModelAndView("/merLogin");
        return mav;
    }
    
    /**
     * 商家注册
     * @return
     */
    @RequestMapping(value = "/toRegister", produces = "text/html;charset=UTF-8")
    public ModelAndView toRegister() {
        ModelAndView mav = new ModelAndView("/business/register");
        return mav;
    }
    
    /**
     * 商家注册成功 填写资料页面
     * @return
     */
    @RequestMapping(value = "/toRegister2", produces = "text/html;charset=UTF-8")
    public ModelAndView toRegister2(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/business/add");
        
        MerchantEntity merchantEntity2 = (MerchantEntity) request.getSession().getAttribute("merchantEntity");
        List<BusinessCategoryEntity> listCategory = businessCategoryService.getAllLevleOne();
        mav.addObject("merchantEntity",merchantEntity2);
        mav.addObject("listCategory",listCategory);
        
        return mav;
    }
    
    /**
     * 验证码发送
     * @param request
     * @return
     */
    @RequestMapping(value = "/toSmsSend", method = RequestMethod.POST)
    public @ResponseBody String toSmsSend(HttpServletRequest request) {
    	
        int code = Util.get6code();
        String userName = request.getParameter("userName");
        
        Boolean flag = SMSClient.send(userName, "您的注册验证码是"+code+"，为了保护您的账户安全，验证短信请勿转发给其他人。【圈城】");
        if (flag) {
            String codeStr = userService.getMobileCode(userName);
            if (codeStr != null && !codeStr.equals("")) {
                userService.updateCodeByMobile(userName, code+"");
            } else {
                userService.saveCode(userName, code+"");
            }
            return "1";
        }else{
            return "0";
        }
    }
    
    /**
     * 商家注册 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toRegisterSave", method = RequestMethod.POST)
    public @ResponseBody int toRegisterSave(HttpServletRequest request,HttpServletResponse response) {
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("password");
        String phone_code = request.getParameter("phone_code");
        String code = userService.getMobileCode(userName);
        
        if (code == null || !code.equals(phone_code)) {
            return 0;
        }
        
        MerchantEntity merchantEntity = merchantService.getMerchantUserName(userName);
        if (merchantEntity.getUserName() != null) {
        	return 2;
        }else {
        	
        	merchantEntity.setUserName(userName);
            merchantEntity.setUserPwd(userPwd);
            merchantEntity.setIsAuth(1);
            
           int flag = merchantService.register(merchantEntity);
           if (1 ==flag) {
               MerchantEntity merchantEntity2 = merchantService.loginMerchant(userName, userPwd);
               if (merchantEntity2.getUserName() != null) {
                   
                   UserCookie cookie= new UserCookie();
                   String ip = getIpAddr(request);
                   String value=ip+"-&&&&&&"+userName+"-&&&&&&"+userPwd;
                   cookie.addCookie(response,"merAutouser",value);
                   
                   request.getSession().setAttribute("merchantEntity", merchantEntity2);
               }
           }
           
           return flag;
        }
    }
    
    /**
     * 登录页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toMerLogin", produces = "text/html;charset=UTF-8")
    public @ResponseBody String toMerLogin(HttpServletRequest request,HttpServletResponse response) {
        
        String userName = request.getParameter("user_name");
        String userPwd = request.getParameter("password");
        
        MerchantEntity merchantEntity2 = merchantService.loginMerchant(userName, userPwd);
        if (merchantEntity2.getUserName() != null) {
            
            UserCookie cookie= new UserCookie();
            String ip = getIpAddr(request);
            String value=ip+"-&&&&&&"+userName+"-&&&&&&"+userPwd;
            cookie.addCookie(response,"merAutouser",value);
            
            request.getSession().setAttribute("merchantEntity", merchantEntity2);
            
            return "1";
        }
        
        return "2";
    }
    
    
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
    /**
     * 忘记密码
     * @return
     */
    @RequestMapping(value = "/toFindPwd", produces = "text/html;charset=UTF-8")
    public ModelAndView toFindPwd() {
        ModelAndView mav = new ModelAndView("/business/find_pwd");
        
        return mav;
    }
    
    @RequestMapping(value = "/toUpdatePws")
    public @ResponseBody int updatePws(HttpServletRequest request,HttpServletResponse response) {

    	String userName = request.getParameter("userName");
    	String password = request.getParameter("password");
    	String phone_code = request.getParameter("phone_code");
        String code = userService.getMobileCode(userName);
        
        int flag = 0;
        
        if (code == null || !code.equals(phone_code)) {
            return 0;
        }
    	
    	 MerchantEntity merchantEntity = merchantService.getMerchantUserName(userName);
    	 if (StringUtil.isNotEmpty(merchantEntity.getUserName())) {
    		 
    		 merchantEntity.setUserPwd(password);
    		 
    		 flag = merchantService.saveMerchant(merchantEntity);
    	 }else {
    		 
    		 merchantEntity.setUserName(userName);
    		 merchantEntity.setUserPwd(password);
    		 
    		 flag = merchantService.register(merchantEntity);
    	 }
    	 
    	 return flag;
    	 
    }
    
    
    
    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/merlogout.do", method = RequestMethod.GET)
    public ModelAndView merlogout(HttpServletRequest request, HttpServletResponse response) {
        // 是当前Session失效
        
        Cookie cookie = new Cookie("merAutouser",null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        
        request.getSession().invalidate();
        
        ModelAndView mav = new ModelAndView("redirect:/toMerchantLogin.do");
        // 将用户请求转发到首页
        return mav;
    }
    
}
